﻿using System;
using System.Text;
using JetBrains.Annotations;
using Kaleida.ServiceMonitor.Framework;

namespace Kaleida.ServiceMonitor.Model.Runtime
{
    public class Operation : IOperation
    {
        private readonly PreparedRequest request;
        private readonly ResponseHandler handler;
        private readonly IWindowsUser windowsUser;

        public Operation([NotNull] PreparedRequest request, [NotNull] ResponseHandler handler, [NotNull] IWindowsUser windowsUser)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (handler == null) throw new ArgumentNullException("handler");
            if (windowsUser == null) throw new ArgumentNullException("windowsUser");

            this.request = request;
            this.handler = handler;
            this.windowsUser = windowsUser;
        }

        public string Description
        {
            get
            {
                var description = new StringBuilder();
                description.Append(request.Description);

                if (handler.Description != "do nothing")
                {
                    description.Append(" and ");
                    description.Append(handler.Description);
                }

                var impersonationUser = windowsUser as NamedWindowsUser;
                if (impersonationUser != null)
                {
                    description.AppendFormat(" (running as {0}\\{1})", impersonationUser.DomainName, impersonationUser.UserName);
                }

                return description.ToString();
            }
        }

        public object Invoke()
        {
            try
            {
                windowsUser.Impersonate();
                return request.GetResponse();
            }
            finally
            {
                windowsUser.Revert();
            }
        }

        public string ProcessResponse(object response)
        {
            return handler.ProcessResponse(response);
        }

        public override string ToString()
        {
            return Description;
        }
    }
    
}
